package com.my.exception;

import com.my.domain.vo.BaseResponseVo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;

import java.sql.SQLException;

/**
 * Created by Administrator on 2017/6/25.
 */
@Log4j
@ControllerAdvice
@PropertySource(value = "classpath:ValidMessages.properties",encoding = "UTF-8",ignoreResourceNotFound = true)
public class GlobalExceptionHandler {

    private static final String DEFAULT_ERROR_VIEW = "error";

    @Value("${SQLExceptionInfo}")
    private String sqlExceptionInfo ;

    @Value("${RunTimeExceptionInfo}")
    private String runTimeExceptionInfo ;


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResponseVo handlerException(Exception e, WebRequest request){
        BaseResponseVo response = new BaseResponseVo();
        log.error("Exception:"+e.getMessage(), e);
        return response;
    }


    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponseVo handlerRuntimeException(RuntimeException ex, HttpServletRequest request) {
        BaseResponseVo response = new BaseResponseVo();
        log.error("RuntimeException:"+ex.getMessage(), ex);
        response.setMessage(runTimeExceptionInfo);
        return response;
    }


    @ExceptionHandler(SQLException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    public BaseResponseVo handlerBusinessException(SQLException e, WebRequest request){
        BaseResponseVo response = new BaseResponseVo();
        log.error("SQLException:"+e.getMessage(), e);
        response.setCode(String.valueOf(e.getErrorCode()));
        response.setMessage(sqlExceptionInfo);
        return response;
    }


}
